package com.useeinfo.oa.modules.security.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.base.tools.EnterpriseTools;
import com.useeinfo.oa.modules.security.dao.OrganizationDao;
import com.useeinfo.oa.modules.security.vo.TreeVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("OrganizationBiz")
public class OrganizationBiz extends CrudBiz<OrganizationDao, Organization> {
    /**
     * 保存子组织
     *
     * @param organization
     * @param parentId
     * @return
     */
    public ResultDto addOrUpdateFirst(Organization organization, String parentId) {
        Organization parent = dao.findModel(StringConverters.null2Long(parentId));
        if (null == organization.getId()) {
            organization.setCreateDate(new Date());
            dao.add(organization);
            if (null != parent) {
                organization.setParentId(parent.getId());
                organization.setParentIds(parent.getParentIds() + organization.getId() + ",");
            }
            organization.setLvl(1);
            dao.update(organization);
        } else {
            Organization organizationEdit = dao.findModel(organization.getId());
            organizationEdit.setOrganizationName(organization.getOrganizationName());
            organizationEdit.setOrganizationDesc(organization.getOrganizationDesc());
            dao.update(organizationEdit);
        }
        return ResultUtil.success();
    }

    /**
     * admin保存组织信息
     *
     * @param organization
     * @param
     * @return
     */
    public ResultDto addOrUpdate(Organization organization, String parentId, Enterprise enterprise) {
        QueryParam queryParam=new QueryParam();
        queryParam.getSqlMap().put("addparentId",parentId);
        queryParam.getSqlMap().put("organizationName",organization.getOrganizationName());
        queryParam.getSqlMap().put("enterpriseId",enterprise.getId()+"");
        List<Organization>organizationList=dao.findList(queryParam);
        //统一节点下不能存在同名部门；
        if (null != organization.getId()) {
            if(CollectionUtils.isNotEmpty(organizationList)){
                return ResultUtil.error("该部门下已经存在相同名称的部门，不能重复添加");
            }
            Organization organizationEdit = dao.findModel(organization.getId());
            organizationEdit.setOrganizationName(organization.getOrganizationName());
            organizationEdit.setOrganizationDesc(organization.getOrganizationDesc());
//            organizationEdit.setEnterprise(enterprise);
            dao.update(organizationEdit);
            organization = organizationEdit;
        } else {
//            if(CollectionUtils.isNotEmpty(organizationList)&&organizationList.size()==1&&!organizationList.get(0).getId().equals(organization.getId())){//编辑改成别的名字有重复
//                return ResultUtil.error("该部门下已经存在相同名称的部门，不能重复添加");
//            }
            if(CollectionUtils.isNotEmpty(organizationList)){
                return ResultUtil.error("该部门下已经存在相同名称的部门，不能重复添加");
            }
            organization.setCreateDate(new Date());
            organization.setEnterprise(enterprise);
            dao.add(organization);
        }

        Organization parent = dao.findModel(StringConverters.null2Long(parentId));
        if (null != parent) {
            organization.setParentId(parent.getId());
            organization.setParentIds(parent.getParentIds() + organization.getId() + ",");
            organization.setLvl(parent.getLvl() + 1);
        } else {
            organization.setParentId(null);
            organization.setParentIds("," + organization.getId() + ",");
            organization.setLvl(1);
        }
        update(organization);
        return ResultUtil.success();
    }


    /**
     * 获取组织--架构的数据信息
     *
     * @param id
     * @return
     */
    public ResultDto getOrganizationMsg(String id, Enterprise enterprise) {
        List<Organization> organizationList = organizationList = new ArrayList<>();
        organizationList.add(dao.findModel(StringConverters.null2Long(id)));
        EnterpriseTools organizationTools = new EnterpriseTools();
        List<EnterpriseTools> organizationToolsList = new ArrayList<>();
        if (id == null) {//查看整个结构
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("lvl", "1");

            organizationList = dao.findList(queryParam);
            if (enterprise == null) {//没获取到企业信息
                organizationTools.setName("企业");
                organizationTools.setId("-1");
            } else {
                organizationTools.setId("-1");
                organizationTools.setName(enterprise.getEnterpriseName());
                String orgHql = "select obj from Organization obj where obj.parentId is null and obj.deleteStatus= false and obj.enterprise.id = "+enterprise.getId();
                organizationList = dao.hqlExcute(orgHql);
            }

            organizationTools.setPid(null);
            List<EnterpriseTools> organizationToolsList1 = new ArrayList<>();
            for (Organization organization : organizationList) {
                EnterpriseTools organizationTools1 = new EnterpriseTools();
                organizationTools1.setId(organization.getId().toString());
                organizationTools1.setName(organization.getOrganizationName());
                if (enterprise == null) {
                    organizationTools1.setPid("1");
                } else {
                    organizationTools1.setPid(enterprise.getId() + "");
                }
                organizationTools1.setChildrens(getChildOrganization(organization));
                organizationToolsList1.add(organizationTools1);
            }
            organizationTools.setChildrens(organizationToolsList1);
            organizationToolsList.add(organizationTools);

        } else {//查看某个组织的结构
            Organization organization = organizationList.get(0);
            organizationTools.setId(organization.getId().toString());
            organizationTools.setName(organization.getOrganizationName());
            organizationTools.setPid(null);
            organizationTools.setChildrens(getChildOrganization(organization));
            organizationToolsList.add(organizationTools);
        }
        return ResultUtil.success(organizationToolsList);

    }

    /**
     * 递归组织的信息
     *
     * @param organization
     * @return
     */
    public List<EnterpriseTools> getChildOrganization(Organization organization) {
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("parentId", organization.getId().toString());
        List<Organization> organizationList = dao.findList(queryParam);
        List<EnterpriseTools> organizationToolsList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(organizationList)) {
            for (Organization organization1 : organizationList) {
                EnterpriseTools organizationTools = new EnterpriseTools();
                organizationTools.setId(organization1.getId().toString());
                organizationTools.setName(organization1.getOrganizationName());
                organizationTools.setPid(organization.getId().toString());
                organizationTools.setChildrens(getChildOrganization(organization1));
                organizationToolsList.add(organizationTools);
            }
        }
        return organizationToolsList;
    }


    public List<Organization> hqlExcute(String hql) {
        return dao.hqlExcute(hql);
    }

    /**
     * 获取所有组织
     *
     * @return
     */
    public ResultDto getOrganizationTree(String sysCode) {
        JSONObject data = new JSONObject();
        List<TreeVO> treeVOList = new ArrayList<>();

        JSONObject menuMap = new JSONObject();
        menuMap.put(sysCode, treeVOList);
        data.put("menuMap", menuMap);

        //选中项
        data.put("roleMenuList", new JSONArray());
        return ResultUtil.success(data);
    }

    /**
     * 根据名称判断是否有该设备分类(有返回 没有返回NULL)
     *
     * @param enterpriseId
     * @return
     */
    public Organization getOrganizationByName(String organizationName,String enterpriseId) {
        if(StringUtils.isBlank(organizationName)||StringUtils.isBlank(enterpriseId)){
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterpriseId+"");
        queryParam.getSqlMap().put("organizationName", organizationName);
        List<Organization> organizationList = this.findList(queryParam);
        if(CollectionUtils.isNotEmpty(organizationList)){
            return organizationList.get(0);
        }
        return null;
    }

    public JSONArray getDashBoardData(List<Object> o,String start,String end,int type){
        JSONArray jsonArray = new JSONArray();
        if(type==1){
            for (int i = 0; i <=23 ; i++) {
                JSONArray detail = new JSONArray();
                int flag = 0;
                detail.add(i);
                for (Object x : o) {
                    if (net.sf.json.JSONArray.fromObject(x).getInt(2)==i) {
                        detail.add(net.sf.json.JSONArray.fromObject(x).get(0));
                        flag = 1;
                    }
                }
                if (flag == 0) {
                    detail.add(0);
                }
                jsonArray.add(detail);
            }
        } else {
            List<String> dateList=DateTimeUtils.getEveryday(start,end);
            for(int i=0;i<dateList.size();i++){
                JSONArray detail = new JSONArray();
                int flag = 0;
                detail.add(i);
                for (Object x : o) {

                    if (net.sf.json.JSONArray.fromObject(x).getString(1).equals(dateList.get(i))) {
                        detail.add(net.sf.json.JSONArray.fromObject(x).get(0));
                        flag = 1;
                    }
                }
                if (flag == 0) {
                    detail.add(0);
                }
                jsonArray.add(detail);
            }
        }
        return jsonArray;

    }
}
